const Service = require('egg').Service;

class serviceChargeService extends Service {


	async update(para) {

		console.log('update');

		const { fee, company_code, type, order_code, remark, out_company_code} = para;

		const sql = this.app.mysql.get('weshop');

		const result0 = await sql.query(
			'select ' +
			'total_price, ' + 
			'out_price ' + 
			'from ' + 
			'wc_bm_account ' + 
			'where ' + 
			'company_code = ? ' +
			'and deposit_system = "0" ' , [out_company_code]);


		console.log('result0');
		console.log(result0);

		if(result0 == undefined || result0.length == 0){
			return false;
		}

		const total_price = result0[0].total_price;
		const out_price = result0[0].out_price;

		const before_money = parseInt(total_price) - parseInt(out_price);
		const after_money = before_money - fee;


		const result = await sql.query(
			'update ' +
			'wc_bm_account ' + 
			'set ' + 
			'out_price = out_price + ? , ' +
			'update_by = ? , ' +
			'update_time = now() ' +
			'where ' + 
			'company_code = ? ' +
			'and deposit_system = "0" ' , [fee, out_company_code, out_company_code]);

		if(result.affectedRows !== 1){
			return false;
		}


		const result1 = await sql.query(
			'insert into wc_bm_account_track( ' +
			'id, ' + 
			'company_code, ' + 
			'deposit_system, ' + 
			'type, ' + 
			'price, ' + 
			'order_code, ' + 
			'create_time, ' + 
			'create_by, ' + 
			'create_company_code, ' + 
			'remark, ' + 
			'before_money, ' + 
			'after_money ' + 
			')values( ' + 
			'uuid(), ' + 
			'?, ' + 
			'"0", ' + 
			'?, ' + 
			'?, ' + 
			'?, ' + 
			'now(), ' + 
			'?, ' + 
			'?, ' + 
			'?, ' + 
			'?, ' + 
			'? ' + 
			')' ,
			[
				out_company_code, 
				type,
				fee,
				order_code,
				company_code,
				company_code,
				remark,
				before_money,
				after_money
			]);

		return result1.affectedRows === 1;
		
	}



  	
}

module.exports = serviceChargeService;

